<?php

namespace app\controller\admin\lineup;

use app\model\admin\lineup\LineupGame;
use app\model\admin\Menu;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Game extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info','jump'];

    protected $relationPrefix = "lineup";
    protected $relationMenuName = "通用阵容工具";
    protected $jumpStyle = [1=>'跳转链接',2=>'跳转工具'];

    public function initialize()
    {
        $this->model = new LineupGame();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                if (isset($item['url']) && !empty($item['url'])) {
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if (isset($item['icon']) && !empty($item['icon'])) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
                $item['jump_style_name'] = $this->jumpStyle[$item['jump_style']];
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
        try {

            Db::startTrans();
            $post['create_time'] = date("Y-m-d H:i:s");
            $post['update_time'] = date("Y-m-d H:i:s");
            if (isset($post['laytpUploadFile'])) unset($post['laytpUploadFile']);
            $id = $this->model->insertGetId($post);
            if ($id) {
                if (!$this->saveMenu($this->relationPrefix . $id, $id, $post['name'])) {
                    return $this->error('添加菜单失败');
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = CommonFun::filterPostData($this->request->post());
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }

        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                $menuModel = new Menu();
                $detail = $menuModel->where("name", $this->relationMenuName)->find();
                if (!$detail) {
                    return $this->error('缺少'.$this->relationMenuName.'菜单');
                }
                $menuModel->where('relation_id', $this->relationPrefix . $post['id'])->where('pid', $detail->id)->save(
                    ['name' => $post['name']]
                );
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    protected function saveMenu($relationId, $gameId, $name)
    {
        $menuModel = new Menu();
        $detail = $menuModel->where("name", $this->relationMenuName)->find();
        if (!$detail) {
            return false;
        } else {
            $detail = $detail->toArray();
            $menuOne = [
                'name' => $name,
                'is_menu' => 1,
                'sort' => 99,
                'pid' => $detail['id'],
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $pid = $menuModel->insertGetId($menuOne);
            if (!$pid) {
                return false;
            }

            //工具样式配置
            $menuLabel = [
                'name' => "工具样式配置",
                'is_menu' => 1,
                'href' => "/admin/lineup/style/index.html?game_id=" . $gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $categoryPid = $menuModel->insertGetId($menuLabel);
            if (!$categoryPid) {
                return false;
            }
            $menuList = [
                ['name' => "新增", 'rule' => '/admin.lineup.style/add?game_id=' . $gameId, 'pid' => $categoryPid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "编辑", 'rule' => '/admin.lineup.style/edit?game_id=' . $gameId, 'pid' => $categoryPid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "显示", 'rule' => '/admin.lineup.style/setStatus', 'pid' => $categoryPid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "删除", 'rule' => '/admin.lineup.style/del?game_id=' . $gameId, 'pid' => $categoryPid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);
            //图鉴配置
            $menuLabel = [
                'name' => "图鉴配置",
                'is_menu' => 1,
                'href' => "/admin/lineup/guide/index.html?game_id=" . $gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $labelPid = $menuModel->insertGetId($menuLabel);
            if (!$labelPid) {
                return false;
            }
            $menuList = [
                ['name' => "编辑", 'rule' => '/admin.lineup.guide/edit?game_id=' . $gameId, 'pid' => $labelPid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "显示", 'rule' => '/admin.lineup.guide/setStatus', 'pid' => $labelPid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);
            //创建组合配置
            $menuModule = [
                'name' => "创建组合配置",
                'is_menu' => 1,
                'href' => "/admin/lineup/team/index.html?game_id=" . $gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $modulePid = $menuModel->insertGetId($menuModule);
            if (!$modulePid) {
                return false;
            }
            $menuList = [
                ['name' => "新增", 'rule' => '/admin.lineup.team/add?game_id=' . $gameId, 'pid' => $modulePid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "编辑", 'rule' => '/admin.lineup.team/edit?game_id=' . $gameId, 'pid' => $modulePid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "显示", 'rule' => '/admin.lineup.team/setStatus', 'pid' => $modulePid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "删除", 'rule' => '/admin.lineup.team/del?game_id=' . $gameId, 'pid' => $modulePid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);

            //组合审核
            $menuNode = [
                'name' => "组合审核",
                'is_menu' => 1,
                'href' => "/admin/lineup/team_audit/index.html?game_id=" . $gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $nodePid = $menuModel->insertGetId($menuNode);
            if (!$nodePid) {
                return false;
            }
            $menuList = [
                ['name' => "编辑", 'rule' => '/admin.lineup.teamAudit/edit?game_id=' . $gameId, 'pid' => $nodePid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "审核", 'rule' => '/admin.lineup.teamAudit/setStatus', 'pid' => $nodePid, 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);
            return true;
        }
    }

    //删除
    public function del()
    {
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try {
            Db::startTrans();
            if ($this->model->destroy($ids)) {
                foreach ($ids as &$item) {
                    $item = $this->relationPrefix . $item;
                }
                (new Menu())->whereIn('relation_id', $ids)->delete();
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                Db::rollback();
                return $this->error('数据删除失败');
            }

        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function jump()
    {
        $data = [];
        foreach ($this->jumpStyle as $key => $item) {
            $data[] = [
                'name' => $item, 'value' => $key
            ];
        }
        return $this->success('获取跳转方式',$data);
    }
}